package com.cxs.controller;

import com.cxs.model.User;
import com.cxs.utils.FileUploadUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project: file-upload-demo
 * @Author: cxs2014501@163.com
 * @Create: 2023/3/6 15:36
 * @Description:
 **/
@WebServlet(name = "fileUploadServlet", urlPatterns = "/upload")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理编码
        req.setCharacterEncoding("utf-8");
        User user = new User();
        //1.先判断上传的数据是否为多段数据（只有多段数据，才是文件上传的）
        if(ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory工程实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据，得到每一个表单项
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {
                        //true普通表单项
                        PropertyDescriptor pd = new PropertyDescriptor(fileItem.getFieldName(), User.class);
                        Method writeMethod = pd.getWriteMethod();
                        writeMethod.invoke(user, fileItem.getString("UTF-8"));
                    } else {
                        // 上传文件，返回路径
                        String filePath = FileUploadUtil.upload(fileItem);
                        user.setAvatar(filePath);
                    }
                }
                System.out.println(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // 非文件上传,直接获取表单值，封装user，做具体操作...
            Map<String, String[]> parameterMap = req.getParameterMap();
        }
        // 进行操作，只是举例
        // userService.sqveUser(user);
    }
}
